<script lang="ts" setup>
import type { DressResourceApi } from '#/api/wedding/dressresource';

import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { getDressResource } from '#/api/wedding/dressresource';

import { Image, Spin, message, Button, Tabs, TabPane } from 'ant-design-vue';

import { parseShareCode, isValidShareCode } from '#/utils/share-code';
import { mergeThemeConfig } from '#/utils/theme-defaults';
import CommentBox from '#/components/wedding/comment/CommentBox.vue';
import CommentList from '#/components/wedding/comment/CommentList.vue';
import CommentStats from '#/components/wedding/comment/CommentStats.vue';

defineOptions({ name: 'DressPreview' });

const route = useRoute();
const router = useRouter();
const loading = ref(true);
const dressData = ref<DressResourceApi.DressResource>();
const commentListRef = ref();

// 获取分享码
const shareCode = computed(() => route.params.id as string);
const dressId = ref<number | null>(null);

// 主题配置（优先使用婚纱配置，否则使用全局配置）
const themeConfig = computed(() => {
  const config = mergeThemeConfig(dressData.value?.mobileThemeConfig);
  console.log('婚纱详情页主题配置:', config);
  return config;
});

// 动态样式
const headerStyle = computed(() => {
  const config = themeConfig.value;
  
  // 构建背景样式
  let background = 'linear-gradient(to right, #ff1493, #9b30ff)'; // 默认渐变
  
  if (config.primaryColor && config.secondaryColor) {
    background = `linear-gradient(135deg, ${config.primaryColor}, ${config.secondaryColor})`;
  }
  
  const style: Record<string, string> = {
    background,
    backgroundSize: 'cover',
    backgroundPosition: 'center',
  };
  
  // 如果有背景图片，添加背景图片
  if (config.backgroundImage) {
    style.backgroundImage = `url(${config.backgroundImage})`;
  }
  
  console.log('婚纱详情页主题配置:', config);
  console.log('婚纱详情页头部样式:', style);
  
  return style;
});

const priceStyle = computed(() => ({
  color: `${themeConfig.value.primaryColor || '#dc143c'} !important`,
}));

// 解析分享码并加载婚纱数据
async function loadDressData() {
  try {
    loading.value = true;
    
    // 验证分享码
    if (!isValidShareCode(shareCode.value)) {
      message.error('分享链接无效或已过期');
      return;
    }
    
    // 解析分享码获取婚纱ID
    const parsedDressId = parseShareCode(shareCode.value);
    if (!parsedDressId) {
      message.error('分享链接无效');
      return;
    }
    
    dressId.value = parsedDressId;
    
    // 加载婚纱数据
    const data = await getDressResource(parsedDressId);
    dressData.value = data;
  } catch (error) {
    message.error('加载婚纱信息失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
}

onMounted(() => {
  loadDressData();
});

// 格式化状态
function formatStatus(status: string) {
  const statusMap = {
    available: { text: '可用', color: '#52c41a' },
    rented: { text: '租赁中', color: '#1890ff' },
    maintenance: { text: '维护中', color: '#faad14' },
    disabled: { text: '停用', color: '#d9d9d9' },
  };
  return statusMap[status as keyof typeof statusMap] || { text: '未知', color: '#d9d9d9' };
}

// 联系客服
function contactService() {
  // 这里可以集成客服系统或跳转到联系页面
  message.info('请联系客服获取更多信息');
}

// 返回主页
function goToHome() {
  // 使用路由跳转到婚纱展示主页，避免页面刷新
  router.push('/wedding/dress-gallery');
}

// 评论成功处理
function handleCommentSuccess() {
  // 刷新评论列表
  if (commentListRef.value) {
    commentListRef.value.refresh();
  }
}
</script>

<template>
  <div class="min-h-screen bg-gray-50">
    <Spin :spinning="loading" size="large">
      <!-- 错误页面 -->
      <div v-if="!loading && !dressData" class="max-w-md mx-auto bg-white min-h-screen flex items-center justify-center">
        <div class="text-center p-8">
          <div class="text-6xl mb-4">🔒</div>
          <h1 class="text-2xl font-bold text-gray-800 mb-2">链接无效</h1>
          <p class="text-gray-600 mb-6">分享链接已过期或无效，请联系管理员获取新的分享链接</p>
          <Button type="primary" @click="goToHome">
            返回主页
          </Button>
        </div>
      </div>
      
      <!-- 正常页面 -->
      <div v-if="dressData" class="max-w-md mx-auto bg-white min-h-screen">
        <!-- 头部 -->
        <div 
          class="text-white p-6 text-center relative" 
          :style="headerStyle"
        >
          <div class="absolute top-4 left-4">
            <Button 
              type="text" 
              class="text-white"
              @click="goToHome"
            >
              ← 返回主页
            </Button>
          </div>
          <h1 class="text-2xl font-bold mb-2">{{ dressData.dressName || '婚纱详情' }}</h1>
          <p class="text-pink-100">{{ dressData.dressCode || '婚纱编码' }}</p>
        </div>

        <!-- 图片展示 -->
        <div v-if="dressData.images && dressData.images.length > 0" class="p-4">
          <h2 class="text-lg font-semibold mb-3 text-gray-800">婚纱图片</h2>
          <Image.PreviewGroup>
            <div class="grid grid-cols-2 gap-3">
              <div 
                v-for="(image, index) in dressData.images" 
                :key="index"
                class="aspect-square rounded-lg overflow-hidden shadow-md"
              >
                <Image
                  :src="image"
                  :alt="`婚纱图片${index + 1}`"
                  class="w-full h-full object-cover"
                  :preview="{ mask: '查看大图' }"
                />
              </div>
            </div>
          </Image.PreviewGroup>
        </div>

        <!-- 价格信息 -->
        <div class="p-4 mx-4 rounded-lg" :style="{ backgroundColor: themeConfig.primaryColor ? `${themeConfig.primaryColor}15` : '#fef2f2' }">
          <h2 class="text-lg font-semibold mb-3 text-gray-800">租赁价格</h2>
          <div class="text-center">
            <div class="text-3xl font-bold mb-2" :style="priceStyle">
              ¥{{ dressData.rentalPrice || 0 }}
            </div>
            <div class="text-gray-600">元/天</div>
          </div>
        </div>

        <!-- 基本信息 -->
        <div class="p-4">
          <h2 class="text-lg font-semibold mb-3 text-gray-800">基本信息</h2>
          <div class="space-y-3">
            <div class="flex justify-between items-center py-3 border-b border-gray-100">
              <span class="text-gray-600">品牌</span>
              <span class="font-medium">{{ dressData.brand || '未设置' }}</span>
            </div>
            <div class="flex justify-between items-center py-3 border-b border-gray-100">
              <span class="text-gray-600">颜色</span>
              <span class="font-medium">{{ dressData.color || '未设置' }}</span>
            </div>
            <div class="flex justify-between items-center py-3 border-b border-gray-100">
              <span class="text-gray-600">尺码</span>
              <span class="font-medium">{{ dressData.size || '未设置' }}</span>
            </div>
            <div class="flex justify-between items-center py-3 border-b border-gray-100">
              <span class="text-gray-600">款式编号</span>
              <span class="font-medium">{{ dressData.style || '未设置' }}</span>
            </div>
            <div class="flex justify-between items-center py-3 border-b border-gray-100">
              <span class="text-gray-600">库存数量</span>
              <span class="font-medium">{{ dressData.inventoryCount || 0 }}件</span>
            </div>
            <div class="flex justify-between items-center py-3">
              <span class="text-gray-600">状态</span>
              <span 
                class="px-3 py-1 rounded-full text-sm font-medium"
                :style="{ 
                  backgroundColor: formatStatus(dressData.status).color + '20',
                  color: formatStatus(dressData.status).color 
                }"
              >
                {{ formatStatus(dressData.status).text }}
              </span>
            </div>
          </div>
        </div>

        <!-- 评论系统 -->
        <div class="p-4 bg-white">
          <Tabs default-active-key="comments">
            <TabPane key="stats" tab="评分统计">
              <CommentStats 
                target-type="dress" 
                :target-id="dressData.id"
              />
            </TabPane>
            
            <TabPane key="comments" tab="用户评论">
              <div class="space-y-4">
                <!-- 评论输入框 -->
                <CommentBox
                  target-type="dress"
                  :target-id="dressData.id"
                  :target-name="dressData.dressName"
                  @success="handleCommentSuccess"
                />
                
                <!-- 评论列表 -->
                <CommentList
                  target-type="dress"
                  :target-id="dressData.id"
                  :show-replies="true"
                  ref="commentListRef"
                />
              </div>
            </TabPane>
          </Tabs>
        </div>

        <!-- 联系信息 -->
        <div class="p-4">
          <h2 class="text-lg font-semibold mb-3 text-gray-800">联系我们</h2>
          <div class="bg-blue-50 p-4 rounded-lg text-center">
            <p class="text-blue-800 mb-3">如需租赁或了解更多详情</p>
            <div class="space-y-2">
              <Button 
                type="primary" 
                size="large" 
                class="w-full"
                @click="contactService"
              >
                联系客服
              </Button>
              <Button 
                size="large" 
                class="w-full"
                @click="goToHome"
              >
                查看更多婚纱
              </Button>
            </div>
          </div>
        </div>

        <!-- 底部 -->
        <div class="p-4 text-center text-gray-500 text-sm">
          <p>© 2024 婚纱租赁管理系统</p>
          <p class="mt-1">扫码查看婚纱详情</p>
          <div class="mt-3">
            <Button 
              type="link" 
              size="small"
              @click="goToHome"
            >
              返回婚纱列表
            </Button>
          </div>
        </div>
      </div>
    </Spin>
  </div>
</template>

<style scoped>
/* 移动端优化样式 */
@media (max-width: 768px) {
  .max-w-md {
    max-width: 100%;
  }
}

/* 确保在移动端正确显示 */
.min-h-screen {
  min-height: 100vh;
}

/* 图片网格优化 */
.grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.aspect-square {
  aspect-ratio: 1;
}
</style>
